#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import importlib

# 设置环境变量
RESOLVE_SCRIPT_API = "/Library/Application Support/Blackmagic Design/DaVinci Resolve/Developer/Scripting"
RESOLVE_SCRIPT_LIB = "/Applications/DaVinci Resolve/DaVinci Resolve.app/Contents/Libraries/Fusion/fusionscript.so"
os.environ['PYTHONPATH'] = os.environ.get('PYTHONPATH', '') + ":" + RESOLVE_SCRIPT_API + "/Modules/"

# 添加DaVinci Resolve脚本API路径到sys.path
sys.path.append(RESOLVE_SCRIPT_API + "/Modules/")

# 现在可以安全地导入DaVinciResolveScript
import DaVinciResolveScript as dvr_script

# 初始化DaVinci Resolve接口
resolve = dvr_script.scriptapp("Resolve")
projectManager = resolve.GetProjectManager()
thisProject = projectManager.GetCurrentProject()
thisTimeline = thisProject.GetCurrentTimeline()

def load_render_preset(event):
    preset = combo.get()
    thisProject.LoadRenderPreset(preset)
    print(f"已选择渲染预设：{preset}")

def add_render_jobs(selected_tracks):
    for track_id in selected_tracks:
        itemOnTimeline = thisTimeline.GetItemListInTrack("video", int(track_id))

        for ele in itemOnTimeline:
            isClip = ele.GetMediaPoolItem()

            if isClip is not None:
                startFrame = ele.GetStart()
                endFrame = ele.GetEnd() - 1
                settings = {"MarkIn": startFrame, "MarkOut": endFrame}
                thisProject.SetRenderSettings(settings)
                thisProject.AddRenderJob()
            else:
                startFrame = ele.GetStart()
                startTimeline = thisTimeline.GetStartFrame()
                frameID = startFrame - startTimeline
                thisTimeline.AddMarker(frameID, "Red", "特殊效果", f"{ele.GetName()}", 1, "none")
                print(f"{ele.GetName()}时间线上包含特殊效果，请检查")
    messagebox.showinfo("完成", "完成添加渲染队列，可以开始渲染了！")

def main():
    root = tk.Tk()
    root.title("选择要渲染的视频轨道与预设")

    tracks = thisTimeline.GetTrackCount("video")
    track_ids = [str(i) for i in range(1, tracks + 1)]
    track_selections = {}

    renderPreset = thisProject.GetRenderPresetList()
    renderPresetList = sorted(renderPreset)

    ttk.Label(root, text="请选择渲染预设：").pack(pady=10)
    global combo
    combo = ttk.Combobox(root, values=renderPresetList)
    combo.bind("<<ComboboxSelected>>", load_render_preset)
    combo.pack(pady=5)

    ttk.Label(root, text="请选择要渲染的视频轨道：").pack(pady=10)
    for track_id in track_ids:
        track_selections[track_id] = tk.BooleanVar()
        tk.Checkbutton(root, text=f"轨道 {track_id}", variable=track_selections[track_id]).pack(anchor='w')

    ttk.Button(root, text="添加渲染任务", command=lambda: add_render_jobs([track_id for track_id, selected in track_selections.items() if selected.get()])).pack(pady=10)

    root.mainloop()

if __name__ == "__main__":
    main()
